package org.ricks.boot;

import org.ricks.boot.utils.DateUtils;
import org.ricks.ioc.RicksContext;
import org.ricks.ioc.utils.Logger;

public abstract class AbstractBootstrap implements ServerBootstrap,Banner {

    public static final String BANNER = "\033[1;35m" +  // 紫色加粗（主标题）
            "\n" +
            "██████╗ ██╗ ██████╗██╗  ██╗███████╗\n" +
            "██╔══██╗██║██╔════╝██║ ██╔╝██╔════╝\n" +
            "██████╔╝██║██║     █████╔╝ ███████╗\n" +
            "██╔══██╗██║██║     ██╔═██╗ ╚════██║\n" +
            "██║  ██║██║╚██████╗██║  ██╗███████║\n" +
            "╚═╝  ╚═╝╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝" +
            "\033[0m" +  // 重置样式
            "\033[1;36m\n" +  // 青色加粗（装饰线）
            "══════════════════════════════════" +
            "\033[0m";

    protected Banner.Mode bannerMode = Banner.Mode.ON;;
    public final String bootstrapName = getClass().getName();

    @Override
    public void printBanner() {
        if(bannerMode == Banner.Mode.ON) {
            System.out.println(BANNER);
        }
    }


    public AbstractBootstrap() {
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(this));
        startBefore();
    }



    @Override
    public void start() {
        long startTime = System.nanoTime();
        try {
            // 打印Banner
            printBanner();
            // 启动逻辑
            this.onStart();

            float interval = DateUtils.formatNanoTime(System.nanoTime() - startTime);
            Logger.info(bootstrapName + " is running, interval="+interval+" ms");

        } catch (Exception e) {
            Logger.error("failed to starting service:{}", e,  bootstrapName);
            System.exit(1);
        }
    }

    @Override
    public void stop() {
        try {
            Logger.info("goodbye " + bootstrapName);
            // 停止逻辑
            this.onStop();
        } catch (Exception e) {
            Logger.error("failed to stopping service:" + bootstrapName,  e);
        } finally {
            // IOC容器销毁
            RicksContext.me().stop();
        }
    }

    protected abstract void onStart();

    protected abstract void onStop();
}

interface Banner {

    void printBanner();


    enum Mode {

        /**
         * Disable printing of the banner.
         */
        OFF,

        /**
         *  printing of the banner.
         */
        ON,

    }
}

